//
//  AppDelegate+HRJSPush.m
//  Hear
//
//  Created by mac on 2017/5/18.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate+HRJSPush.h"

#import <JPUSHService.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#import "HRFMDBDynamicNotifacationTool.h"
#import "HRDynamicNotificationModel.h"
#import "HRDynamicViewController.h"
#import "HRFollowDyanmicInfoViewController.h"
#import "HRCircleOfFirendsViewController.h"
#import "Hear_SingleShowViewController.h"

#import "HRFollowDynamicViewController.h"

@implementation AppDelegate (HRJSPush)

- (void)setupJSPush{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    DDLog(@"%@",USERID);
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段，key是自己定义的
}

- (void)getNewPushNotification:(NSDictionary *)userInfo {

    NSDictionary *contentDict = [userInfo[@"Content"] jsonValueDecoded];
    
    if ([contentDict[@"type"] intValue] == 1 || [contentDict[@"type"] intValue] == 2|| [contentDict[@"type"] intValue] == 4 || [contentDict[@"type"] intValue] == 5 || [contentDict[@"type"] intValue] == 9 || [contentDict[@"type"] intValue] == 10 || [contentDict[@"type"] intValue] == 12 || [contentDict[@"type"] intValue] == 13 || [contentDict[@"type"] intValue] == 14){// 1评论  2点赞
        HRDynamicNotificationModel *notiModel = [HRDynamicNotificationModel new];
        
        notiModel.currentUserID = USERID;
        notiModel.type = contentDict[@"type"];
        notiModel.message = contentDict[@"Message"];
        notiModel.content = contentDict[@"content"]?contentDict[@"content"]:@"";
        notiModel.postTime = [self getCurrentTime];
        notiModel.fromUserID = contentDict[@"fromUserId"]?contentDict[@"fromUserId"]:@"";
        notiModel.messageID = contentDict[@"dynamicID"]?contentDict[@"dynamicID"]:@"";
        notiModel.isRead = @"0";
        notiModel.icon = contentDict[@"UserPictureName"]?contentDict[@"UserPictureName"]:@"";
        notiModel.nickName = contentDict[@"nickname"]?contentDict[@"nickname"]:@"";
        notiModel.iconColor = contentDict[@"UserPictureBackgroundColor"]?contentDict[@"UserPictureBackgroundColor"]:@"";
        
//        NSArray *currentMotifiArr = [[HRFMDBDynamicNotifacationTool sharedInstance]selectAllContent];
//        for (HRDynamicNotificationModel *model in currentMotifiArr) {
//            if (![model.type isEqualToString:notiModel.type] && [model.messageID isEqualToString:notiModel.messageID]){
//                [[HRFMDBDynamicNotifacationTool sharedInstance] insertContacts:notiModel];
//                [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//                [[EMCDDeviceManager sharedInstance] playVibration];
//            }
//        }
        [[HRFMDBDynamicNotifacationTool sharedInstance] insertContacts:notiModel];
        [[EMCDDeviceManager sharedInstance] playNewMessageSound];
        [[EMCDDeviceManager sharedInstance] playVibration];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];


        if ([notiModel.type intValue] == 10){ // 申请好友通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newFirendsNotifi" object:nil];

            return;
        }
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"newMessageNotifi"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"newMesageNotifi" object:nil];

        
    }else if ([contentDict[@"type"] intValue] == 3){
        
    }else if ([contentDict[@"type"] intValue] == 6){
        
    }else if ([contentDict[@"type"] intValue] == 7){
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteAppTopicUserNotifi" object:nil];
    }else if ([contentDict[@"type"] intValue] == 8){
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"getMatchUserInfoNotifi" object:contentDict];
    }
}


#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert);

    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容

    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    NSDictionary *userDict = content.userInfo;


    [self getNewPushNotification:userInfo];
    DDLog(@"");
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();

    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容

    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    NSDictionary *userDict = content.userInfo;
    NSDictionary *contentDict = [userInfo[@"Content"] jsonValueDecoded];

    /**
     * 自定义接收器
     *
     * 如果不定义这个 Receiver，则：
     * 1) 默认用户会打开主界面
     * 2) 接收不到自定义消息
     * public enum PushType
     {
     comment = 1,    //评论
     like = 2,       //点赞
     picture = 3,    //
     follow=4,       //关注
     moments=5,      //发表新动态推送给粉丝
     invitation=6,   //邀请
     stopMatch=7,    //停止匹配
     getMatch = 8,   //匹配
     soundLike=9,    //唱片点赞
     friendRequest=10,  //好友请求
     momentRefresh=11,  //朋友圈刷新
     commentSound=12,//留声机评论
     answerQuestion=13,//回答留声机话题推送给题主
     answerHot=14,//回答留声机被推荐到热门
     }
     */

//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//    [[EMCDDeviceManager sharedInstance] playVibration];

    if ([contentDict[@"type"] intValue] == 1 || [contentDict[@"type"] intValue] == 2|| [contentDict[@"type"] intValue] == 4 || [contentDict[@"type"] intValue] == 5 || [contentDict[@"type"] intValue] == 9 || [contentDict[@"type"] intValue] == 10 || [contentDict[@"type"] intValue] == 12 || [contentDict[@"type"] intValue] == 13 || [contentDict[@"type"] intValue] == 14){// 1评论  2点赞 4 关注推送 5关注的人发了动态  10申请好友通知
        HRDynamicNotificationModel *notiModel = [HRDynamicNotificationModel new];

        notiModel.currentUserID = USERID;
        notiModel.type = contentDict[@"type"];
        notiModel.message = contentDict[@"Message"];
        notiModel.content = contentDict[@"content"]?contentDict[@"content"]:@"";
        notiModel.postTime = [self getCurrentTime];
        notiModel.fromUserID = contentDict[@"fromUserId"]?contentDict[@"fromUserId"]:@"";
        notiModel.messageID = contentDict[@"dynamicID"]?contentDict[@"dynamicID"]:@"";
        notiModel.isRead = @"1";
        notiModel.icon = contentDict[@"UserPictureName"]?contentDict[@"UserPictureName"]:@"";
        notiModel.nickName = contentDict[@"nickName"]?contentDict[@"nickName"]:@"";
        notiModel.iconColor = contentDict[@"UserPictureBackgroundColor"]?contentDict[@"UserPictureBackgroundColor"]:@"";
//        UIApplicationState state = [UIApplication sharedApplication].applicationState;
            if ([notiModel.type intValue]== 2 ||[notiModel.type intValue]== 9){
                notiModel.isRead = @"0";
            }

            [[HRFMDBDynamicNotifacationTool sharedInstance] insertContacts:notiModel];

            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"newMessageNotifi"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newMesageNotifi" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];


        UIViewController *VC = VIEWCCONTROLER;

        if ([notiModel.type intValue]== 4){
            HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
            dynamicVC.currentUserID = notiModel.messageID;
            [VIEWCCONTROLER.navigationController pushViewController:dynamicVC animated:YES];
        }else if ([notiModel.type intValue]== 1  || [notiModel.type intValue]== 5){
            HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
            infoVC.dynamicID = notiModel.messageID;

            [VIEWCCONTROLER.navigationController pushViewController:infoVC animated:YES];
        }else if ([notiModel.type intValue]== 2 ||[notiModel.type intValue]== 9){
//            HRCircleOfFirendsViewController *VC = [HRCircleOfFirendsViewController new];
//            VC.selectedTabIndex =1;
            HRFollowDynamicViewController *VC = [HRFollowDynamicViewController new];
            [VIEWCCONTROLER.navigationController pushViewController:VC animated:YES];

        }

        if ([contentDict[@"type"] intValue] == 13 || [contentDict[@"type"] intValue] == 14) {
            Hear_SingleShowViewController *vc = [Hear_SingleShowViewController new];
            vc.soundID = notiModel.messageID;
            [VIEWCCONTROLER.navigationController pushViewController:vc animated:YES];
        }

    }else if ([contentDict[@"type"] intValue] == 3){

    }else if ([contentDict[@"type"] intValue] == 6){

    }else if ([contentDict[@"type"] intValue] == 7){
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteAppTopicUserNotifi" object:nil];
    }else if ([contentDict[@"type"] intValue] == 8){
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"getMatchUserInfoNotifi" object:contentDict];
    }

//    if([userDict[@"ConversationChatter"] intValue]){
//
//        EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:userInfo[@"ConversationChatter"] conversationType:EMConversationTypeChat];
//        messgaeVC.jz_navigationBarBackgroundHidden = NO;
//        messgaeVC.otherNickNameStr = self.infModel.NickName;
//        messgaeVC.otherIconStr = self.infModel.UserPictureBackgroundColor;
//        messgaeVC.otherIconName = self.infModel.UserPictureName;
//        messgaeVC.title = self.infModel.NickName;
//        [VIEWCCONTROLER.navigationController pushViewController:messgaeVC animated:YES];
//
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"newMesageNotifi" object:nil];
//
//    }
    DDLog(@"");
}

- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

@end
